﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using NPMonitor.DataModel;
using NPMonitor.Implementation;
using NPMonitor.Web.Code;

namespace NPMonitor.Web.UserControls
{
    public partial class WorkflowInfo : BaseUserControl
    {
        /// <summary>
        /// 每行索引
        /// </summary>
        protected int itemIndex = 1;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindControl();
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            rfvJob.ErrorMessage = ValidationString.RequiredOneJob;
            rfvName.ErrorMessage = ValidationString.FieldRequired.FormatString("workflow name");
            rfvAction.ErrorMessage = ValidationString.RequiredOneAction;
            cvSelectJob.ErrorMessage = ValidationString.RequiredOneJob;

            this.Page.Form.DefaultButton = btnSaveJob.UniqueID;
        }

        /// <summary>
        /// 绑定下拉框数据
        /// </summary>
        protected void BindControl()
        {
            List<JobDefinition> list = StoreManager.Current.JobDefinitionStore.GetAllJobDefinitions(0, 999);
            ddlJob.DataValueField = "JobId";
            ddlJob.DataTextField = "JobName";
            ddlJob.DataSource = list;
            ddlJob.DataBind();
            ddlJob.Items.Insert(0, new ListItem("Select", ""));

            ddlAction.Items.Add(new ListItem("Continue", "Continue"));
            ddlAction.Items.Add(new ListItem("Stop", "Stop"));
        }

        /// <summary>
        /// 绑定Repter控件
        /// </summary>
        protected void BindRepeter()
        {
            if (WorkflowId != null)
            {
                List<WorkflowJobData> list = StoreManager.Current.WorkflowStore.GetWorkflowJobDataByWorkflowId(WorkflowId.Value);
                rptJobs.DataSource = list;
                rptJobs.DataBind();

                hfSequence.Value = list.Count().ToString();
                hfJobItems.Value = JsonConvert.SerializeObject(list);
                ItemsCount = list.Count();
            }
        }

        /// <summary>
        /// 保持Workflow信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            string strJobItems = hfJobItems.Value;
            List<WorkflowJobItem> list = (List<WorkflowJobItem>)JsonConvert.DeserializeObject(strJobItems, typeof(List<WorkflowJobItem>));
            WorkflowData info = new WorkflowData();
            info.WorkflowName = txtName.Text.Trim();
            info.Description = txtDesc.Text.Trim();
            if (WorkflowId != null)
            {
                info.WorkflowId = WorkflowId;
                info.UpdateBy = CurrentUser;
            }
            else
            {
                info.CreateBy = CurrentUser;
            }

            try
            {
                StoreManager.Current.WorkflowStore.SaveWorkflowInfo(info, list);
                ParentPage.ShowSuccessfulDiv();
            }
            catch
            {
                JsUtil.Alert(CommonString.SaveFailedTip, this.Page);
            }

            ClearControlText();

            //重新绑定父页面的Workflow列表
            ParentPage.BindWorkflowList();
        }

        /// <summary>
        /// 清空文本控件内容
        /// </summary>
        public void ClearControlText()
        {
            txtDesc.Text = "";
            txtName.Text = "";
            hfJobItems.Value = "";
            rptJobs.DataSource = null;
            rptJobs.DataBind();
            ItemsCount = 0;
            WorkflowId = null;
        }

        /// <summary>
        /// 根据workflow id 获取workflow基本信息、并显示当前workflow下的所有job
        /// </summary>
        /// <param name="workflowId"></param>
        public void ShowWorkflowInfo(int workflowId)
        {
            WorkflowId = workflowId;
            WorkflowData info = StoreManager.Current.WorkflowStore.GetWorkflowDataById(workflowId);
            if (info != null)
            {
                txtDesc.Text = info.Description;
                txtName.Text = info.WorkflowName;
            }
            BindRepeter();
            this.Page.Form.DefaultButton = btnSaveJob.UniqueID;
        }

        /// <summary>
        /// Workflow Id
        /// </summary>
        public int? WorkflowId
        {
            get
            {
                if (ViewState["WorkflowId"] != null)
                {
                    return Convert.ToInt32(ViewState["WorkflowId"]);
                }
                else
                {
                    return null;
                }
            }
            set
            {
                ViewState["WorkflowId"] = value;
            }
        }

        /// <summary>
        /// 父页面对象
        /// </summary>
        public WorkflowManagement ParentPage
        {
            get
            {
                return this.Page as WorkflowManagement;
            }
        }

        /// <summary>
        /// 机器记录总数
        /// </summary>
        public int ItemsCount
        {
            get
            {
                return Convert.ToInt32(ViewState["WorkflowJobItemsCount"]);
            }

            set
            {
                ViewState["WorkflowJobItemsCount"] = value;
            }
        }
    }
}